package com.mbw.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mbw.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class CommonLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	@Value("${spring.security.loginType}")
	private String loginType;
	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
										HttpServletResponse response,
										Authentication authentication) throws IOException, ServletException {
		if ("JSON".equalsIgnoreCase(loginType)){
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(objectMapper.writeValueAsString(Result.ok()));
		}else {
			//跳转到上一次请求的页面上
			super.onAuthenticationSuccess(request, response, authentication);
		}

	}
}
